<template>
  <a-modal
    title="修改"
    v-model="show"
    :maskClosable="false"
    :width="1050"
    placement="right"
    :closable="true"
    @cancel="onClose"
    :footer="null"
    :visible="reconSceneEditVisiable"
  >

    <a-form :form="firstForm">

      <a-row>
        <a-col :md="12" :sm="20" v-show="false">
          <a-form-item label="instId"
                       v-bind="formItemLayout">
            <a-input v-decorator="['instId']"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="20" v-show="false">
          <a-form-item label="id"
                       v-bind="formItemLayout">
            <a-input v-decorator="['id']"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="20">
          <a-form-item label="对账场景"
                       v-bind="formItemLayout">
            <a-input v-decorator="['reconSceneId',{rules: [{ required: true, message: '必填' }]}]"/>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="20">
          <a-form-item label='对账场景描述'
                       v-bind="formItemLayout">
            <a-input v-decorator="['reconSceneDesc']"/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="20">
          <a-form-item label="节假日是否对账"
                       v-bind="formItemLayout">
            <a-select
              mode="default"
              :allowClear="true"
              style="width: 100%"
              v-decorator="['reconAtHolday']">
              <a-select-option key="Y">对账</a-select-option>
              <a-select-option key="N">不对账</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="12" :sm="20">
          <a-form-item label='触发的最小文件日期'
                       v-bind="formItemLayout">
            <a-date-picker
              placeholder="请选择日期"
              name="birthday"
              v-decorator="['minFileDate']"
              format="YYYYMMDD"/>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="12" :sm="20">
          <a-form-item label="补号表达式"
                       v-bind="formItemLayout">
            <a-input v-decorator="['fillExpression']"/>
          </a-form-item>
        </a-col>
      </a-row>
      <br>

    </a-form>

    <div v-if="submitFlag" class="operator">
      <a-button type="primary" @click="add">新增</a-button>
    </div>
    <br>
    <!-- 表格区域 -->
    <a-table ref="TableInfo"
             :columns="columns"
             :rowKey="(record,index)=>{return index}"
             :dataSource="dataSource"
             :pagination="pagination"
             :loading="loading"
             :scroll="{ x: 900 }"
             :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
             @change="handleTableChange">
      <template v-if="submitFlag" slot="operation" slot-scope="text, record">
        <a-icon type="setting" style="color: #4a9ff5" @click="edit(record)"
                title="修改"/>&nbsp;&nbsp;
        <a-popconfirm title="确定删除？" @confirm="reconSceneInfoDelete(record)" okText="确定" cancelText="取消">
          <a-icon type="delete" style="color: #42b983" title="删除"/>&nbsp;&nbsp;
        </a-popconfirm>&nbsp;&nbsp;
      </template>
    </a-table>
    <br>

    <a-row v-if="submitFlag">
      <a-col :span="30" style="text-align: center">
        <a-button @click="submitForm" type="primary">提交</a-button>
        <a-popconfirm title="确定放弃编辑？" @confirm="onClose" okText="确定" cancelText="取消">
          <a-button style="margin-right: .8rem">取消</a-button>
        </a-popconfirm>
      </a-col>
    </a-row>


    <!-- 修改对账场景信息 -->
    <reconSceneInfo-input
      ref="ReconSceneInfoInput"
      @success="handleReconSceneInfoEditSuccess"
      @close="handleReconSceneInfoEditClose"
      :reconSceneInfoInputVisiable="reconSceneInfoInputVisiable">
    </reconSceneInfo-input>

  </a-modal>
</template>

<script>
  import ReconSceneInfoInput from "./ReconSceneInfoInput";
  import moment from "moment";
  import reconPath from '../reconPath/ReconPath'

  moment.locale('zh-cn');
  const formItemLayout = {
    labelCol: {span: 6},
    wrapperCol: {span: 14}
  }

  export default {
    name: "ReconSceneEdit",
    props: {
      reconSceneEditVisiable: {
        default: false
      }
    },
    components: {ReconSceneInfoInput},

      data() {
      return {
        formItemLayout,
        firstForm: this.$form.createForm(this),
        dataSource: [],
        selectedRowKeys: [],
        queryParams: {},
        filteredInfo: null,
        sortedInfo: null,
        paginationInfo: null,
        pagination: {
          pageSizeOptions: ['10', '20', '30', '40', '100'],
          defaultCurrent: 1,
          defaultPageSize: 10,
          showQuickJumper: true,
          showSizeChanger: true,
          showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
        },
        loading: false,
        reconSceneInfoInputVisiable: false,
        submitFlag: false,
        reconSceneId: '',
        reconSceneInputInstId: ''
      }
    },

    computed: {
      columns() {
        let {sortedInfo, filteredInfo} = this
        sortedInfo = sortedInfo || {}
        filteredInfo = filteredInfo || {}
        return [{
          title: '对账关联系统',
          dataIndex: 'reconSysId',
          width: 130
        }, {
          title: '对账关联系统描述',
          dataIndex: 'reconSysSceneDesc',
          width: 160,
          ellipsis: true
        }, {
          title: '对账文件日期',
          dataIndex: 'reconFileDate',
          width: 130
        }, {
          title: '对账文件状态',
          dataIndex: 'reconFileStatus',
          width: 150,
          sorter: false,
          ellipsis: true,
          customRender: (text, row, index) => {
            switch (text) {
              case '0':
                return '就绪';
              case '1':
                return '运行中';
              case '2':
                return '运行中有新文件';
              case '3':
                return '运行完成';
              case '4':
                return '运行完成有遗留数据';
              // case '4':
              //     return '文件运行完成有遗留数据有新文件';
              default:
                return text
            }
          }
        }, {
          title: '系统日期类型',
          dataIndex: 'sysDateType',
          width: 130
        }, {
          title: '系统并发基数',
          dataIndex: 'taskNum',
          width: 130
        }, {
          title: '最晚到达时间',
          dataIndex: 'lastArrivedTime',
          width: 130
        }, {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: {customRender: 'operation'},
          fixed: 'right',
          width: 130
        }]
      },
      show: {
        get: function () {
          return this.reconSceneEditVisiable
        },
        set: function () {
        }
      }
  },

    methods: {
      reconSceneInfoDelete(record){
        console.log(record);
        console.log(this.dataSource);
        let deleteIndex = 0;
        for(let index=0; index<this.dataSource.length; index++){
          if(record.id === this.dataSource[index].id){
            deleteIndex = index;
          }
        }
        this.dataSource.splice(deleteIndex,1);
      },

      onClose() {
        this.firstForm.resetFields()
        this.$emit('close')
      },


      setFormValues(record, optFlag) {
        console.log(record.id)
        this.reconSceneId = record.reconSceneId
        this.reconSceneInputInstId = record.instId
        this.firstForm.getFieldDecorator('instId');
        this.firstForm.setFieldsValue({'instId': record.instId});
        // this.firstForm.getFieldDecorator('optFlag');
        // this.firstForm.setFieldsValue({'optFlag': record.optFlag});
        optFlag = "update"
        if (optFlag == "update" || optFlag == "view") {
          this.firstForm.getFieldDecorator('id');
          this.firstForm.setFieldsValue({'id': record.id}); // + Math.random() * 1000
          this.firstForm.getFieldDecorator('reconSceneId');
          this.firstForm.setFieldsValue({'reconSceneId': record.reconSceneId});
          this.firstForm.getFieldDecorator('reconSceneDesc');
          this.firstForm.setFieldsValue({'reconSceneDesc': record.reconSceneDesc});
          this.firstForm.getFieldDecorator('minFileDate');
          this.firstForm.setFieldsValue({'minFileDate': moment(record.minFileDate)});
          this.firstForm.getFieldDecorator('reconAtHolday');
          this.firstForm.setFieldsValue({'reconAtHolday': record.reconAtHolday});
          this.firstForm.getFieldDecorator('fillExpression');
          this.firstForm.setFieldsValue({'fillExpression': record.fillExpression});
        }
        if ("add" == optFlag || "update" == optFlag) {
          this.submitFlag = true;
          var oprDataIndex = "operation";
          var exits = false;
          for (var i = 0; i < this.columns.length; i++) {
            var column = this.columns[i];
            if (column.dataIndex == oprDataIndex) {
              exits = true;
            }
          }
          if (!exits) {
            var column = {
              title: '操作',
              dataIndex: 'operation',
              scopedSlots: {customRender: 'operation'},
              fixed: 'right',
              width: 130
            };
            this.columns.push(column);
          }
        } else {
          this.submitFlag = false;
          for (var i = 0; i < this.columns.length; i++) {
            var column = this.columns[i];
            if (column.dataIndex == "operation") {
              this.columns.splice(i, 1);
            }
          }
        }
        let params = {}
        params.instId = this.reconSceneInputInstId;
        params.reconSceneId = this.reconSceneId;
        // console.log("reconSceneId:--------------------------" + this.reconSceneId)
        // console.log("instId:--------------------------" + this.reconSceneInputInstId)
        let {sortedInfo, filteredInfo} = this
        let sortField, sortOrder
        // 获取当前列的排序和列的过滤规则
        if (sortedInfo) {
          sortField = sortedInfo.field
          sortOrder = sortedInfo.order
        }
        this.fetch({
          sortField: sortField,
          sortOrder: sortOrder,
          ...params,
          ...filteredInfo
        })
        console.log("pagination.total:--------------------------" + this.pagination.total)
      },
      submitForm() {
        this.firstForm.validateFields((err, values) => {
          console.log(values)
          if (!err) {
            let reconSceneStat = {};
            reconSceneStat.oprId = this.userId;
            reconSceneStat.id = values.id;
            reconSceneStat.instId = values.instId;
            reconSceneStat.reconSceneId = values.reconSceneId;
            reconSceneStat.reconSceneDesc = values.reconSceneDesc;
            reconSceneStat.minFileDate = moment(values.minFileDate).format("YYYYMMDD");
            reconSceneStat.reconAtHolday = values.reconAtHolday;
            reconSceneStat.fillExpression = values.fillExpression;
            reconSceneStat.reconSceneInfoJson = JSON.stringify(this.dataSource);
            if (values.id && values.id != null && values.id.toString() != "") {
              //修改
              this.$post('/admin/csmc/reconscene/update', {
                ...reconSceneStat
              }).then((r) => {
                this.firstForm.resetFields();
                this.$emit('success', '修改对账场景信息成功');
              });
            } else {
              //新增
              this.$post('/admin/csmc/reconscene/add', {
                ...reconSceneStat
              }).then((r) => {
                this.firstForm.resetFields();
                this.$emit('success', '新增对账场景信息成功');
              });
            }
          }
        })
      },
      onSelectChange(selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys
      },
      add() {
        this.reconSceneInfoInputVisiable = true;
        var record = {};
        record.instId = this.firstForm.getFieldValue("instId");
        var curIndex = this.dataSource.length <= 0 ? 0 : this.dataSource.length - 1;
        this.$refs.ReconSceneInfoInput.setFormValues(record, curIndex, "add");
      },
      getCurIndex(data) {
        var curIndex = -1;
        if (this.dataSource.length > 0) {
          this.dataSource.forEach((item, index, array) => {
            if (item.id == data.id && item.instId == data.instId && item.reconSysId == data.reconSysId) {
              curIndex = index;
            }
          });
          if (curIndex == -1) {
            curIndex = this.dataSource.length <= 0 ? 0 : this.dataSource.length - 1;
          }
        } else {
          curIndex = 0;
        }
        return curIndex;
      },
      edit(record) {
        this.reconSceneInfoInputVisiable = true;
        var curIndex = this.getCurIndex(record);
        this.$refs.ReconSceneInfoInput.setFormValues(record, curIndex, "update");
      },
      handleReconSceneInfoEditClose() {
        this.reconSceneInfoInputVisiable = false
      },
      handleReconSceneInfoEditSuccess(data) {
        this.reconSceneInfoInputVisiable = false;
        let dbReconSysStat = null
        this.$get('/admin/csmc/reconscene/getReconSysStat', {
          instId : this.reconSceneInputInstId,
        }).then( res=> {
          dbReconSysStat = res.data.data;
          for(let index=0; index<dbReconSysStat.length; index++){
            if(data.reconSysId==dbReconSysStat[index].reconSysId){
              this.$message.error(data.reconSysId+"对账关联系统已存在");
              return;
            }
          }
          if ("add" == data.optFlag) {
            this.dataSource.push(data);
            if (this.paginationInfo && this.paginationInfo.pageSize) {
              this.paginationInfo.pageSize = this.paginationInfo.pageSize + 1;
            }
          } else {
            /* 通过 this.dataSource.forEach 遍历赋值后并不会通过数据双向绑定更新dataSource里的内容 */
            for (var i = 0; i < this.dataSource.length; i++) {
              if (data.curIndex == i) {
                var item = this.dataSource[i];
                item.id = data.id;
                item.instId = data.instId;
                item.reconSysStatId = data.reconSysStatId;
                item.reconSysId = data.reconSysId;
                item.reconSysSceneDesc = data.reconSysSceneDesc;
                item.reconFileDate = data.reconFileDate;
                item.reconFileStatus = data.reconFileStatus;
                item.sysDateType = data.sysDateType;
                item.taskNum = data.taskNum;
                item.lastArrivedTime = data.lastArrivedTime;
              }
            }
          }
          /*if (data.optFlag == "add") {
              this.$message.success('新增成功');
          } else {
              this.$message.success('修改成功');
          }*/
          // this.fetch()
          console.log(this.dataSource);
        })
      },
      handleTableChange(pagination, filters, sorter){
        // 将这三个参数赋值给Vue data，用于后续使用
        this.paginationInfo = pagination
        // 重置列过滤器规则
        this.filteredInfo = null
        // 重置列排序规则
        this.sortedInfo = sorter

        // this.reconSceneInfo.visiable = false
        this.fetch({
          sortField: sorter.field,
          sortOrder: sorter.order,
          ...this.queryParams,
          ...filters
        })
      },
      fetch(params = {}) {
        this.loading = true
        if (this.paginationInfo) {
          // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
          this.$refs.TableInfo.pagination.current = this.paginationInfo.current
          this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
          params.pageSize = this.paginationInfo.pageSize
          params.pageNum = this.paginationInfo.current
        } else {
          // 如果分页信息为空，则设置为默认值
          params.pageSize = this.pagination.defaultPageSize
          params.pageNum = this.pagination.defaultCurrent
        }
        this.$get('/admin/csmc//reconscene/sublist', {
          ...params
        }).then((r) => {
          let data = r.data
          const pagination = {...this.pagination}
          pagination.total = data.total
          this.dataSource = data.rows
          this.pagination = pagination
          this.loading = false
        })
      }
    }
  }
</script>

<style scoped>

</style>
